package com.purong.purong.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.purong.purong.Contant;
import com.purong.purong.R;
import com.purong.purong.adapter.HotCityAdapter;
import com.purong.purong.adapter.LocationAdapter;
import com.purong.purong.bean.AreaBean;
import com.purong.purong.bean.LocationBean;
import com.purong.purong.util.CharacterParser;
import com.purong.purong.util.CommonUtil;
import com.purong.purong.util.PinyinComparator;
import com.purong.purong.widget.ExtGridLayoutManager;
import com.purong.purong.widget.LoadingView;
import com.purong.purong.widget.SideBar;
import com.yao.sdk.net.ResponseInfo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by user on 2017/9/15.
 */
public class LocationActivity extends BaseActivity {
    private View headView;
    private LinearLayout headLay;
    private EditText mEditText;
    public TextView dialog;
    private SideBar mSidBar;
    private RecyclerView mRecyclerView;
    private RecyclerView mHotRecyclerView;
    private TextView locationCity,locationIng;
    private LinearLayout nowLoactionLay,hotCityLay;
    private List<AreaBean> sourceDataList=new ArrayList<>();
    private List<AreaBean> dataList=new ArrayList<>();
    private List<AreaBean> hotList=new ArrayList<>();
    private LocationAdapter mAdapter;
    private HotCityAdapter mHotAdapter;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private int mWidth,mheight;
    private AreaBean mArea;
    private LoadingView loadingView;

    @Override
    public int getRootViewId() {
        return R.layout.activity_location;
    }

    @Override
    public void initBundle() {
        mArea=(AreaBean)getIntent().getSerializableExtra("LOCATION_AREA");
        initAction();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initAction(){
        addAction(Contant.LOCATION_ACTION, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                mArea=(AreaBean)intent.getSerializableExtra("object");
                if (mArea!=null&&mArea.getAcronym()!=null){
                    Log.e("zwj","....receive="+mArea.getAcronym());
                    locationIng.setVisibility(View.GONE);
                    nowLoactionLay.setVisibility(View.VISIBLE);
                    locationCity.setText(mArea.getAcronym());
                }
            }
        });
    }
    public void initView(){
        showTitle("城市选择");
        showLeft(R.drawable.home_icon_close, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LocationActivity.this.finish();
            }
        });
        loadingView=(LoadingView)findViewById(R.id.loading_view);
        loadingView.setLoadListener(new LoadingView.OnLoadListener() {
            @Override
            public void onReload() {
                getLocation();
            }

            @Override
            public void onRefresh() {

            }
        });
        mWidth= (CommonUtil.getScreenWidth(this)-CommonUtil.dip2px(this,78))/3;
        mheight=CommonUtil.dip2px(this,31);
        headView = getLayoutInflater().inflate(R.layout.location_list_head,null);
        headLay=(LinearLayout)headView.findViewById(R.id.head_lay);
        locationCity=(TextView)headView.findViewById(R.id.location_city);
        nowLoactionLay=(LinearLayout) headView.findViewById(R.id.now_loaction_lay);
        hotCityLay=(LinearLayout)headView.findViewById(R.id.hot_city_lay);
        locationIng=(TextView)headView.findViewById(R.id.location_ing);
        locationCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.putExtra("LOCATION_AREA",mArea);
                setResult(RESULT_OK,intent);
                LocationActivity.this.finish();
            }
        });
        locationCity.setMinWidth(mWidth);
        if (mArea!=null&&mArea.getAcronym()!=null){
            locationIng.setVisibility(View.GONE);
            nowLoactionLay.setVisibility(View.VISIBLE);
            locationCity.setText(mArea.getAcronym());
        }else {
            locationIng.setVisibility(View.VISIBLE);
            nowLoactionLay.setVisibility(View.GONE);
        }
        mHotRecyclerView=(RecyclerView)headView.findViewById(R.id.hot_city_recycler);
        mHotAdapter=new HotCityAdapter(this,mWidth,mheight);
        mHotAdapter.setData(hotList);
        mHotRecyclerView.setLayoutManager(new ExtGridLayoutManager(this,3));
        mHotRecyclerView.setAdapter(mHotAdapter);
        mHotAdapter.setOnAreaClickListener(new HotCityAdapter.OnAreaClickListener() {
            @Override
            public void onClick(AreaBean area) {
                Intent intent=new Intent();
                intent.putExtra("LOCATION_AREA",area);
                setResult(RESULT_OK,intent);
                LocationActivity.this.finish();
            }
        });
        mRecyclerView=(RecyclerView)findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter=new LocationAdapter();

        mAdapter.setData(sourceDataList);
        mAdapter.addHeaderView(headView);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnAreaClickListener(new LocationAdapter.OnAreaClickListener() {
            @Override
            public void onClick(AreaBean area) {
                Intent intent=new Intent();
                intent.putExtra("LOCATION_AREA",area);
                setResult(RESULT_OK,intent);
                LocationActivity.this.finish();
            }
        });
        characterParser = CharacterParser.getInstance();
        pinyinComparator = PinyinComparator.getInstance();
        mSidBar = (SideBar)findViewById(R.id.sidrbar);
        dialog = (TextView)findViewById(R.id.group_dialog);
        mSidBar.setTextView(dialog);
        mSidBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                if (dataList.size() == 0) {
                    return;
                }
                int position = mAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    ((LinearLayoutManager)mRecyclerView.getLayoutManager()).scrollToPositionWithOffset(position+1,0);
                }

            }
        });
        mEditText=(EditText)findViewById(R.id.edit_text);
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() != 0) {
                    headLay.setVisibility(View.GONE);

                } else {
                    headLay.setVisibility(View.VISIBLE);
                    ((LinearLayoutManager)mRecyclerView.getLayoutManager()).scrollToPositionWithOffset(0,0);
                }
            }
        });
    }

    @Override
    public void initData() {
        getLocation();
    }

    private void getLocation(){
        loadingView.loading();
        Map<String, String> params = new LinkedHashMap<String, String>();
        if (!request(Contant.LOCATION, params, true, false)){
            loadingView.fail();
        }
    }

    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy()){
            return;
        }
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.LOCATION)){
            if (responseInfo.isOk){
                try{
                    LocationBean bean= JSON.parseObject(responseInfo.content,LocationBean.class);


                    if (bean.getArea_list().getAllArea()!=null){
                        dataList.addAll(bean.getArea_list().getAllArea());
                    }
                    setData();
                    if (bean.getArea_list().getHot()!=null&&bean.getArea_list().getHot().size()>0){
                        hotList.addAll(bean.getArea_list().getHot());
                        mHotAdapter.notifyDataSetChanged();
                    }else {
                        hotCityLay.setVisibility(View.GONE);
                    }
                    loadingView.finish();
                }catch (Exception e){
                    loadingView.fail();
                }

            }else {
                loadingView.fail();
            }
        }
    }

    public void setData() {
        sourceDataList.clear();
        if (dataList != null && dataList.size() > 0) {

            sourceDataList.addAll(filledData(dataList));
//                    sourceDataList = ; //过滤数据为有字母的字段  现在有字母 别的数据没有
        }

        //还原除了带字母字段的其他数据
        for (int i = 0; i < dataList.size(); i++) {
            sourceDataList.get(i).setAcronym(dataList.get(i).getAcronym());
            sourceDataList.get(i).setArea_name(dataList.get(i).getArea_name());
            sourceDataList.get(i).setArea_id(dataList.get(i).getArea_id());
            sourceDataList.get(i).setIs_hot(dataList.get(i).getIs_hot());
        }

        // 根据a-z进行排序源数据
        Collections.sort(sourceDataList, pinyinComparator);
        mAdapter.notifyDataSetChanged();
//                adapter = new FriendAdapter(getActivity(), sourceDataList);
//                mListView.setAdapter(adapter);
    }

    private List<AreaBean> filledData(List<AreaBean> list) {
        ArrayList<AreaBean> mFriendList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            AreaBean friendModel = new AreaBean();

            friendModel.setAcronym(list.get(i).getAcronym());
            //汉字转换成拼音
            String pinyin;
            pinyin = characterParser.getSelling(list.get(i).getAcronym());

            String sortString;
            if (pinyin.equals("")) {
                sortString = "";
            } else {
                sortString = pinyin.substring(0, 1).toUpperCase();
            }


            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                friendModel.setLetters(sortString.toUpperCase());
            } else {
                friendModel.setLetters("#");
            }

            mFriendList.add(friendModel);
        }
        return mFriendList;

    }

    private void filterData(String filterStr) {
        List<AreaBean> filterDateList = new ArrayList<>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = sourceDataList;
        } else {
            filterDateList.clear();
            for (AreaBean friendModel : sourceDataList) {
                String name;
                name = friendModel.getAcronym();
                if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(friendModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        mAdapter.updateListView(filterDateList);
    }

//    public void onClick(View v){
//        switch (v.getId()){
//            case R.id.location_city:
//                showToast("当前定位城市");
//                break;
//        }
//    }
}
